#!/usr/bin/env python3
"""
Record对话框 - 显示所有被修改的行信息
"""

from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QWidget,
                               QPushButton, QTextEdit, QLabel, QTableWidget,
                               QTableWidgetItem, QHeaderView, QMessageBox,
                               QFileDialog, QSplitter, QFrame, QLineEdit, QComboBox)
from PySide6.QtCore import Qt, QSize
from PySide6.QtGui import QFont, QColor, QIcon
from typing import List, Dict, Any
import json
from datetime import datetime


class RecordDialog(QDialog):
    """Record对话框 - 显示所有被修改的行信息"""
    
    def __init__(self, modified_rows: List[Dict[str, Any]], headers: List[str], parent=None):
        super().__init__(parent)
        self.modified_rows = modified_rows
        self.headers = headers
        self.filtered_rows = modified_rows[:]  # 用于筛选的行数据副本
        
        self.setWindowTitle("修改记录 - Record")
        self.setGeometry(100, 100, 1400, 900)
        self.setModal(True)
        
        self._setup_ui()
        self._load_data()
        self._setup_styles()
        
    def _setup_styles(self):
        """设置样式"""
        # 设置整体样式表
        self.setStyleSheet("""
            QDialog {
                background-color: #f0f0f0;
            }
            QLabel {
                color: #333333;
                font-family: "Microsoft YaHei", Arial, sans-serif;
            }
            QTableWidget {
                background-color: white;
                alternate-background-color: #f9f9f9;
                selection-background-color: #0078d4;
                selection-color: white;
                gridline-color: #e0e0e0;
                border: 1px solid #d0d0d0;
            }
            QTableWidget::item {
                padding: 4px;
            }
            QTextEdit {
                background-color: white;
                border: 1px solid #d0d0d0;
                border-radius: 4px;
            }
            QPushButton {
                background-color: #0078d4;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                font-family: "Microsoft YaHei", Arial, sans-serif;
            }
            QPushButton:hover {
                background-color: #106ebe;
            }
            QPushButton:pressed {
                background-color: #005a9e;
            }
            QPushButton#closeButton {
                background-color: #d83b01;
            }
            QPushButton#closeButton:hover {
                background-color: #a52a00;
            }
        """)
        
        # 设置标题样式
        for label in self.findChildren(QLabel):
            if label.text() == "修改记录汇总":
                label.setStyleSheet("""
                    QLabel {
                        color: #0078d4;
                        font-weight: bold;
                        font-size: 16px;
                        padding: 10px;
                    }
                """)
            elif label.text() == "修改行列表" or label.text() == "行详细信息":
                label.setStyleSheet("""
                    QLabel {
                        color: #333333;
                        font-weight: bold;
                        font-size: 12px;
                        padding: 5px;
                    }
                """)
        
        # 设置按钮样式
        for button in self.findChildren(QPushButton):
            if button.text() == "关闭":
                button.setObjectName("closeButton")
                
    def _setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        
        # 标题
        title_label = QLabel("修改记录汇总")
        title_font = QFont()
        title_font.setPointSize(14)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(title_label)
        
        # 搜索和筛选区域
        filter_layout = QHBoxLayout()
        
        # 搜索框
        self.search_edit = QLineEdit()
        self.search_edit.setPlaceholderText("搜索行号...")
        self.search_edit.textChanged.connect(self._filter_data)
        filter_layout.addWidget(QLabel("搜索:"))
        filter_layout.addWidget(self.search_edit)
        
        # 类型筛选
        self.type_combo = QComboBox()
        self.type_combo.addItem("全部类型", "")
        self.type_combo.addItem("单元格修改", "cell_modified")
        self.type_combo.addItem("新增行", "row_added")
        self.type_combo.addItem("删除行", "row_deleted")
        self.type_combo.addItem("禁用行", "row_disabled")
        self.type_combo.currentIndexChanged.connect(self._filter_data)
        filter_layout.addWidget(QLabel("类型:"))
        filter_layout.addWidget(self.type_combo)
        
        # 重置按钮
        reset_btn = QPushButton("重置")
        reset_btn.clicked.connect(self._reset_filters)
        filter_layout.addWidget(reset_btn)
        
        layout.addLayout(filter_layout)
        
        # 统计信息
        stats_text = f"总共有 {len(self.modified_rows)} 行被修改"
        self.stats_label = QLabel(stats_text)
        self.stats_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.stats_label)
        
        # 分割器
        splitter = QSplitter(Qt.Horizontal)
        layout.addWidget(splitter)
        
        # 左侧：修改行列表
        left_frame = QFrame()
        left_frame.setFrameStyle(QFrame.StyledPanel)
        left_layout = QVBoxLayout(left_frame)
        
        left_title = QLabel("修改行列表")
        left_title.setFont(QFont("Arial", 10, QFont.Bold))
        left_layout.addWidget(left_title)
        
        self.row_table = QTableWidget()
        self.row_table.setColumnCount(4)
        self.row_table.setHorizontalHeaderLabels(["行号", "修改类型", "修改列数", "状态"])
        self.row_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.row_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.row_table.itemSelectionChanged.connect(self._on_row_selected)
        left_layout.addWidget(self.row_table)
        
        splitter.addWidget(left_frame)
        
        # 右侧：详细信息
        right_frame = QFrame()
        right_frame.setFrameStyle(QFrame.StyledPanel)
        right_layout = QVBoxLayout(right_frame)
        
        right_title = QLabel("行详细信息")
        right_title.setFont(QFont("Arial", 10, QFont.Bold))
        right_layout.addWidget(right_title)
        
        self.detail_text = QTextEdit()
        self.detail_text.setReadOnly(True)
        self.detail_text.setFont(QFont("Consolas", 9))
        right_layout.addWidget(self.detail_text)
        
        splitter.addWidget(right_frame)
        
        # 设置分割器比例
        splitter.setSizes([400, 800])
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        # 导出按钮
        export_btn = QPushButton("导出记录")
        export_btn.clicked.connect(self._export_record)
        button_layout.addWidget(export_btn)
        
        # 清空记录按钮
        clear_btn = QPushButton("清空记录")
        clear_btn.clicked.connect(self._clear_record)
        button_layout.addWidget(clear_btn)
        
        button_layout.addStretch()
        
        # 关闭按钮
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.accept)
        button_layout.addWidget(close_btn)
        
        layout.addLayout(button_layout)
        
    def _load_data(self):
        """加载数据"""
        self.row_table.setRowCount(len(self.modified_rows))
        
        for i, row_data in enumerate(self.modified_rows):
            # 行号
            row_item = QTableWidgetItem(str(row_data['row_index']))
            row_item.setData(Qt.UserRole, row_data)
            self.row_table.setItem(i, 0, row_item)
            
            # 修改类型
            mod_type = row_data['modification_type']
            type_text = self._get_modification_type_text(mod_type)
            type_item = QTableWidgetItem(type_text)
            self.row_table.setItem(i, 1, type_item)
            
            # 修改列数
            col_count = len(row_data.get('modified_columns', []))
            col_item = QTableWidgetItem(str(col_count))
            self.row_table.setItem(i, 2, col_item)
            
            # 状态
            status_text = self._get_status_text(row_data)
            status_item = QTableWidgetItem(status_text)
            self.row_table.setItem(i, 3, status_item)
            
            # 设置行颜色
            self._set_row_color(i, mod_type)
        
        # 选择第一行
        if self.row_table.rowCount() > 0:
            self.row_table.selectRow(0)
            self._show_row_detail(self.modified_rows[0])
    
    def _get_modification_type_text(self, mod_type: str) -> str:
        """获取修改类型的中文描述"""
        type_map = {
            'cell_modified': '单元格修改',
            'row_added': '新增行',
            'row_deleted': '删除行',
            'row_disabled': '禁用行'
        }
        return type_map.get(mod_type, mod_type)
    
    def _get_status_text(self, row_data: Dict[str, Any]) -> str:
        """获取状态文本"""
        mod_type = row_data['modification_type']
        if mod_type == 'row_deleted':
            return "已删除"
        elif mod_type == 'row_disabled':
            return "已禁用"
        elif mod_type == 'row_added':
            return "新增"
        else:
            return "已修改"
    
    def _set_row_color(self, row: int, mod_type: str):
        """设置行颜色"""
        color_map = {
            'cell_modified': QColor(255, 255, 200),  # 浅黄色
            'row_added': QColor(200, 255, 200),      # 浅绿色
            'row_deleted': QColor(255, 200, 200),    # 浅红色
            'row_disabled': QColor(200, 200, 200)    # 浅灰色
        }
        
        color = color_map.get(mod_type, QColor(255, 255, 255))
        for col in range(self.row_table.columnCount()):
            item = self.row_table.item(row, col)
            if item:
                item.setBackground(color)
    
    def _on_row_selected(self):
        """行选择改变事件"""
        current_row = self.row_table.currentRow()
        if current_row >= 0:
            item = self.row_table.item(current_row, 0)
            if item:
                row_data = item.data(Qt.UserRole)
                self._show_row_detail(row_data)
    
    def _show_row_detail(self, row_data: Dict[str, Any]):
        """显示行详细信息"""
        detail_text = f"行号: {row_data['row_index']}\n"
        detail_text += f"修改类型: {self._get_modification_type_text(row_data['modification_type'])}\n"
        detail_text += f"修改时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
        
        if row_data['modification_type'] == 'row_deleted':
            detail_text += "该行已被删除，无法显示数据。\n"
        elif row_data['full_row_data']:
            detail_text += "完整行数据:\n"
            detail_text += "-" * 50 + "\n"
            
            # 显示表头
            header_line = "列号\t列名\t\t数据\n"
            detail_text += header_line
            detail_text += "-" * 50 + "\n"
            
            # 显示数据
            for i, (header, value) in enumerate(zip(self.headers, row_data['full_row_data'])):
                # 检查是否被修改
                is_modified = i in row_data.get('modified_columns', [])
                marker = "★" if is_modified else " "
                
                # 格式化显示
                col_info = f"{i}\t{header:<15}\t{marker} {value}\n"
                detail_text += col_info
            
            # 显示修改的列
            modified_cols = row_data.get('modified_columns', [])
            if modified_cols:
                detail_text += "\n修改的列: " + ", ".join(map(str, modified_cols)) + "\n"
        else:
            detail_text += "无法获取行数据。\n"
        
        self.detail_text.setText(detail_text)
    
    def _export_record(self):
        """导出记录"""
        if not self.modified_rows:
            QMessageBox.information(self, "提示", "没有修改记录可导出。")
            return
        
        # 选择保存文件
        file_path, _ = QFileDialog.getSaveFileName(
            self,
            "导出修改记录",
            f"modified_rows_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
            "JSON文件 (*.json);;所有文件 (*)"
        )
        
        if file_path:
            try:
                # 准备导出数据
                export_data = {
                    'export_time': datetime.now().isoformat(),
                    'total_modified_rows': len(self.modified_rows),
                    'headers': self.headers,
                    'modified_rows': self.modified_rows
                }
                
                # 保存文件
                with open(file_path, 'w', encoding='utf-8') as f:
                    json.dump(export_data, f, ensure_ascii=False, indent=2)
                
                QMessageBox.information(self, "成功", f"修改记录已导出到:\n{file_path}")
                
            except Exception as e:
                QMessageBox.critical(self, "错误", f"导出失败:\n{str(e)}")
    
    def _clear_record(self):
        """清空记录"""
        reply = QMessageBox.question(
            self,
            "确认清空",
            "确定要清空所有修改记录吗？\n此操作不可撤销。",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            # 发送清空信号
            self.accept()
            return True
        
        return False

    def _filter_data(self):
        """筛选数据"""
        # 获取筛选条件
        search_text = self.search_edit.text().strip()
        selected_type = self.type_combo.currentData()
        
        # 筛选数据
        self.filtered_rows = []
        for row_data in self.modified_rows:
            # 按行号搜索
            if search_text:
                if str(row_data['row_index']).find(search_text) == -1:
                    continue
            
            # 按类型筛选
            if selected_type and row_data['modification_type'] != selected_type:
                continue
                
            self.filtered_rows.append(row_data)
        
        # 更新表格显示
        self._update_table_display()
        # 更新统计信息
        self._update_stats()
    
    def _reset_filters(self):
        """重置筛选条件"""
        self.search_edit.clear()
        self.type_combo.setCurrentIndex(0)
        self.filtered_rows = self.modified_rows[:]
        self._update_table_display()
        self._update_stats()
    
    def _update_table_display(self):
        """更新表格显示"""
        self.row_table.setRowCount(len(self.filtered_rows))
        
        for i, row_data in enumerate(self.filtered_rows):
            # 行号
            row_item = QTableWidgetItem(str(row_data['row_index']))
            row_item.setData(Qt.UserRole, row_data)
            self.row_table.setItem(i, 0, row_item)
            
            # 修改类型
            mod_type = row_data['modification_type']
            type_text = self._get_modification_type_text(mod_type)
            type_item = QTableWidgetItem(type_text)
            self.row_table.setItem(i, 1, type_item)
            
            # 修改列数
            col_count = len(row_data.get('modified_columns', []))
            col_item = QTableWidgetItem(str(col_count))
            self.row_table.setItem(i, 2, col_item)
            
            # 状态
            status_text = self._get_status_text(row_data)
            status_item = QTableWidgetItem(status_text)
            self.row_table.setItem(i, 3, status_item)
            
            # 设置行颜色
            self._set_row_color(i, mod_type)
    
    def _update_stats(self):
        """更新统计信息"""
        stats_text = f"显示 {len(self.filtered_rows)} 行，总共 {len(self.modified_rows)} 行被修改"
        self.stats_label.setText(stats_text)
